#!/usr/bin/env node

const http=require('http'),
      fs = require('fs'),
      qs = require('querystring');
let items = [];

function genPage(){
  let html = fs.readFileSync('./template.html').toString('utf-8');
  html = html.replace('xxx',items.map(i => '<li>' + i + '</li>').join('\n'));
  return html;
}
http.createServer((req,res)=>{
  //status code       
  //header,txt/html
  if(req.url !== '/'){
    res.statusCode=404;
    res.setHeader('content-type','text/html');
    res.end('<h1>Not found</h1>');
    return;
  }
  let data = '';
  req.on('data', chunk => data+=chunk);
  req.on('end', () => {
    let item = qs.parse(data).item;
  
    if(item !== '' && typeof item !== 'undefined') items.push(item);
    res.writeHead(200,{
      'content-type':'text/html',
      'content-length':Buffer.byteLength(genPage())
    });
    
    // res.statusCode = 200;
    // res.setHeader('Content-type','text/html')
    // res.setHeader('Content-length',Buffer.byteLength(html));//求html的字节长度
    // 完成响应数据的封装
    res.end(genPage());
  });
}).listen(8080);
